﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin.SkinControl;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductLine;
using ERP_SaaS_WinForm.生产计划_派单_车间.CarManage;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class ProductLineManage : Form
    {
        // 按钮控件声明
        private SkinButton btnAdd;
        private SkinButton btnClear;
        
        // 车间数据列表
        private List<CarData> carList = new List<CarData>();
        
        // 生产线数据列表
        private List<ProductLineData> productLineList = new List<ProductLineData>();
        
        // 生产线信息显示控件
        private SkinDataGridView dgvProductLines;
        private SkinButton btnRefresh;
        
        public ProductLineManage()
        {
            InitializeComponent();
            InitializeAddProductLineControls();
            InitializeProductLineInfoPage();
        }
        
        /// <summary>
        /// 初始化新增生产线页面的控件
        /// </summary>
        private async void InitializeAddProductLineControls()
        {
            try
            {
                // 设置生产线类型下拉框的选项
                cboLineType.Items.Clear();
                cboLineType.Items.AddRange(new object[] { "类型一", "类型二", "类型三" });
                cboLineType.DropDownStyle = ComboBoxStyle.DropDownList;
                
                // 设置输入框的水印文本
                txtLineCode.WaterText = "请输入生产线编号";
                txtLineName.WaterText = "请输入生产线名称";
                
                // 设置车间下拉框
                cboCarLine.DropDownStyle = ComboBoxStyle.DropDownList;
                cboCarLine.WaterText = "请选择车间";
                
                // 加载车间数据
                await LoadCarDataAsync();
                
                // 新增按钮
                btnAdd = new SkinButton();
                btnAdd.Location = new Point(197, 220);
                btnAdd.Size = new Size(100, 35);
                btnAdd.Text = "新增";
                btnAdd.Font = new Font("微软雅黑", 9F);
                btnAdd.Click += BtnAdd_Click;
                tabAddProductLine.Controls.Add(btnAdd);
                
                // 清空按钮
                btnClear = new SkinButton();
                btnClear.Location = new Point(310, 220);
                btnClear.Size = new Size(100, 35);
                btnClear.Text = "清空";
                btnClear.Font = new Font("微软雅黑", 9F);
                btnClear.Click += BtnClear_Click;
                tabAddProductLine.Controls.Add(btnClear);
                
                Console.WriteLine("新增生产线页面控件初始化完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化控件时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 初始化生产线信息页面
        /// </summary>
        private void InitializeProductLineInfoPage()
        {
            try
            {
                // 创建DataGridView
                dgvProductLines = new SkinDataGridView();
                dgvProductLines.Location = new Point(20, 20);
                dgvProductLines.Size = new Size(1700, 500);
                dgvProductLines.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                dgvProductLines.AllowUserToAddRows = false;
                dgvProductLines.ReadOnly = true;
                dgvProductLines.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvProductLines.MultiSelect = false;
                dgvProductLines.BackgroundColor = Color.White;
                dgvProductLines.BorderStyle = BorderStyle.None;
                dgvProductLines.GridColor = Color.LightGray;
                dgvProductLines.Font = new Font("微软雅黑", 9F);
                dgvProductLines.ScrollBars = ScrollBars.Both;
                
                // 设置列
                dgvProductLines.Columns.Clear();
                dgvProductLines.Columns.Add("LineCode", "生产线编号");
                dgvProductLines.Columns.Add("LineName", "生产线名称");
                dgvProductLines.Columns.Add("LineType", "生产线类型");
                dgvProductLines.Columns.Add("CarId", "车间ID");
                
                // 设置合适的列宽 - 总宽度约520像素，适合在1700像素宽度内显示
                dgvProductLines.Columns["LineCode"].Width = 140;   // 生产线编号
                dgvProductLines.Columns["LineName"].Width = 200;   // 生产线名称
                dgvProductLines.Columns["LineType"].Width = 100;   // 生产线类型
                dgvProductLines.Columns["CarId"].Width = 80;       // 车间ID
                
                // 设置列的最小宽度，防止用户调整时过小
                dgvProductLines.Columns["LineCode"].MinimumWidth = 100;
                dgvProductLines.Columns["LineName"].MinimumWidth = 150;
                dgvProductLines.Columns["LineType"].MinimumWidth = 80;
                dgvProductLines.Columns["CarId"].MinimumWidth = 60;
                
                // 允许用户调整列宽
                dgvProductLines.AllowUserToResizeColumns = true;
                
                // 设置列头样式
                dgvProductLines.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
                dgvProductLines.ColumnHeadersDefaultCellStyle.BackColor = Color.LightBlue;
                dgvProductLines.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black;
                dgvProductLines.ColumnHeadersHeight = 30;
                
                // 设置行样式
                dgvProductLines.DefaultCellStyle.Font = new Font("微软雅黑", 9F);
                dgvProductLines.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue;
                dgvProductLines.RowTemplate.Height = 25;
                
                // 创建刷新按钮
                btnRefresh = new SkinButton();
                btnRefresh.Location = new Point(20, 540);
                btnRefresh.Size = new Size(100, 35);
                btnRefresh.Text = "刷新";
                btnRefresh.Font = new Font("微软雅黑", 9F);
                btnRefresh.Click += BtnRefresh_Click;
                
                // 添加控件到页面
                tabProductLine.Controls.Add(dgvProductLines);
                tabProductLine.Controls.Add(btnRefresh);
                
                // 加载生产线数据
                LoadProductLineDataAsync();
                
                Console.WriteLine("生产线信息页面初始化完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化生产线信息页面时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        
        /// <summary>
        /// 加载车间数据
        /// </summary>
        private async Task LoadCarDataAsync()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    var response = await client.GetAsync("http://localhost:5281/api/Car/GetCar");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();
                        var apiResponse = JsonConvert.DeserializeObject<ApiCarInfoResponse>(responseContent);
                        
                        if (apiResponse.code == 200 && apiResponse.data != null)
                        {
                            carList = apiResponse.data;
                            
                            // 填充下拉框
                            cboCarLine.Items.Clear();
                            foreach (var car in carList)
                            {
                                cboCarLine.Items.Add(car.CarName);
                            }
                            
                            Console.WriteLine($"成功加载 {carList.Count} 个车间数据");
                        }
                        else
                        {
                            MessageBox.Show($"加载车间数据失败: {apiResponse.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"HTTP请求失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载车间数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 加载生产线数据
        /// </summary>
        private async void LoadProductLineDataAsync()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    var response = await client.GetAsync("http://localhost:5281/api/Car/GetProductLine");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();
                        var apiResponse = JsonConvert.DeserializeObject<ApiProductLineInfoResponse>(responseContent);
                        
                        if (apiResponse.code == 200 && apiResponse.data != null)
                        {
                            productLineList = apiResponse.data;
                            
                            // 清空DataGridView
                            dgvProductLines.Rows.Clear();
                            
                            // 填充数据
                            foreach (var productLine in productLineList)
                            {
                                string lineTypeText = GetLineTypeText(productLine.LineType);
                                dgvProductLines.Rows.Add(
                                    productLine.LineCode,
                                    productLine.LineName,
                                    lineTypeText,
                                    productLine.CarId
                                );
                            }
                            
                            Console.WriteLine($"成功加载 {productLineList.Count} 条生产线数据");
                        }
                        else
                        {
                            MessageBox.Show($"加载生产线数据失败: {apiResponse.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"HTTP请求失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载生产线数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 获取生产线类型文本
        /// </summary>
        private string GetLineTypeText(int lineType)
        {
            switch (lineType)
            {
                case 1: return "类型一";
                case 2: return "类型二";
                case 3: return "类型三";
                default: return $"类型{lineType}";
            }
        }
        
        /// <summary>
        /// 刷新按钮点击事件
        /// </summary>
        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            LoadProductLineDataAsync();
        }
        
        /// <summary>
        /// 新增按钮点击事件
        /// </summary>
        private async void BtnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrWhiteSpace(txtLineCode.Text))
                {
                    MessageBox.Show("请输入生产线编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtLineCode.Focus();
                    return;
                }
                
                if (string.IsNullOrWhiteSpace(txtLineName.Text))
                {
                    MessageBox.Show("请输入生产线名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtLineName.Focus();
                    return;
                }
                
                if (cboLineType.SelectedIndex == -1)
                {
                    MessageBox.Show("请选择生产线类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cboLineType.Focus();
                    return;
                }
                
                if (cboCarLine.SelectedIndex == -1)
                {
                    MessageBox.Show("请选择所在车间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cboCarLine.Focus();
                    return;
                }
                
                // 获取选中的车间ID
                int selectedCarId = 0;
                if (cboCarLine.SelectedIndex >= 0 && cboCarLine.SelectedIndex < carList.Count)
                {
                    // 假设CarCode是数字字符串，转换为int
                    var selectedCar = carList[cboCarLine.SelectedIndex];
                    if (int.TryParse(selectedCar.CarCode, out selectedCarId))
                    {
                        // 转换成功
                    }
                    else
                    {
                        // 如果CarCode不是数字，使用索引+1作为ID
                        selectedCarId = cboCarLine.SelectedIndex + 1;
                    }
                }
                
                // 准备请求数据
                var productLineData = new ProductLineData
                {
                    LineCode = txtLineCode.Text.Trim(),
                    LineName = txtLineName.Text.Trim(),
                    LineType = cboLineType.SelectedIndex + 1, // 1=类型一, 2=类型二, 3=类型三
                    CarId = selectedCarId
                };
                
                // 调用API
                bool success = await AddProductLineAsync(productLineData);
                
                if (success)
                {
                    MessageBox.Show("生产线添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearForm();
                    
                    // 自动刷新生产线信息显示
                    LoadProductLineDataAsync();
                    
                    // 切换到生产线信息页面
                    skinTabControl1.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加生产线时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 清空按钮点击事件
        /// </summary>
        private void BtnClear_Click(object sender, EventArgs e)
        {
            ClearForm();
        }
        
        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            txtLineCode.Text = "";
            txtLineName.Text = "";
            cboLineType.SelectedIndex = -1;
            cboCarLine.SelectedIndex = -1;
            txtLineCode.Focus();
        }
        
        /// <summary>
        /// 调用API添加生产线
        /// </summary>
        /// <param name="productLineData">生产线数据</param>
        /// <returns>是否成功</returns>
        private async Task<bool> AddProductLineAsync(ProductLineData productLineData)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 准备请求内容
                    var jsonContent = JsonConvert.SerializeObject(productLineData);
                    var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                    
                    // 发送POST请求
                    var response = await client.PostAsync("http://localhost:5281/api/Car/AddProductLine", content);
                    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();
                        var apiResponse = JsonConvert.DeserializeObject<ApiProductLineResponse>(responseContent);
                        
                        if (apiResponse.code == 200)
                        {
                            Console.WriteLine("生产线添加成功");
                            return true;
                        }
                        else
                        {
                            MessageBox.Show($"添加失败: {apiResponse.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }
                    }
                    else
                    {
                        MessageBox.Show($"HTTP请求失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"API调用失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
    }
}
